﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Text;
using System.Xml;
using Common.Utilities;
using Common.Utilities.Dispatcher;

namespace Workflows.Components.TextMining.Collapse
{
    /// <summary>
    /// 
    /// </summary>
    [Serializable]
    public class TableStatsOutput:ResultBase
    {
        #region props
        private int _TotalRecordCount;
        /// <summary></summary>
        public int TotalRecordCount
        {
            get
            {
                return this._TotalRecordCount;
            }
            set
            {
                this._TotalRecordCount = value;
            }
        }

        private Dictionary<string,TableFieldStats<IComparable>> _FieldStats;
        /// <summary></summary>
        public Dictionary<string,TableFieldStats<IComparable>> FieldStats
        {
            get
            {
                return this._FieldStats;
            }
            set
            {
                this._FieldStats = value;
            }
        }
        #endregion

        #region ctor
        /// <summary>
        /// 
        /// </summary>
        public TableStatsOutput():base(Guid.Empty,Guid.Empty)
        {
            this._TotalRecordCount = 0;
            this._FieldStats = null;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="componentID"></param>
        /// <param name="jobTicketID"></param>
        /// <param name="totalRecs"></param>
        /// <param name="fieldStats"></param>
        public TableStatsOutput(Guid componentID, Guid jobTicketID, int totalRecs, Dictionary<string,TableFieldStats<IComparable>> fieldStats) 
            : base(componentID, jobTicketID)
        {
            this._TotalRecordCount = totalRecs;
            this._FieldStats = fieldStats;
        }
        #endregion

        /// <summary>
        /// 
        /// </summary>
        /// <param name="xDoc"></param>
        /// <param name="parentNode"></param>
        /// <returns></returns>
        public override XmlNode Serialize(ref XmlDocument xDoc, ref XmlNode parentNode)
        {
            XmlNode xNode = XmlDataUtil.AddElement(ref xDoc, parentNode, "Output");
            XmlDataUtil.UpdateAttribute(ref xDoc, xNode, "Type", this.GetType().FullName);
            XmlDataUtil.UpdateAttribute(ref xDoc, xNode, "WorkerID", this.OwnerWorkerInstanceID.ToString());
            XmlDataUtil.UpdateAttribute(ref xDoc, xNode, "FinishTime", this.FinishTime.ToString());

            XmlDataUtil.UpdateAttribute(ref xDoc, xNode,"TotalRecordCount",this.TotalRecordCount.ToString());
            if(this._FieldStats !=null && this._FieldStats.Count>0)
            {
                XmlNode fieldStatsRootNode = XmlDataUtil.AddElement(ref xDoc, xNode, "FieldStats");
                foreach(string fieldName in this._FieldStats.Keys)
                {
                    TableFieldStats<IComparable> fieldStats = this._FieldStats[fieldName];
                    XmlNode fieldNode = XmlDataUtil.AddElement(ref xDoc, fieldStatsRootNode, "Field");
                    XmlDataUtil.UpdateAttribute(ref xDoc, fieldNode, "FieldName", fieldName);
                    XmlDataUtil.UpdateAttribute(ref xDoc,fieldNode,"DbType",((int)fieldStats.DbType).ToString());
                    XmlDataUtil.UpdateAttribute(ref xDoc, fieldNode, "NonNullValueCount", fieldStats.NonNullValueCount.ToString());
                    XmlDataUtil.UpdateAttribute(ref xDoc,fieldNode,"NonNullValueCoverage",fieldStats.NonNullValueCoverage.ToString());
                    XmlDataUtil.UpdateAttribute(ref xDoc,fieldNode,"DistinctCount",fieldStats.DistinctCount.ToString());
                    XmlDataUtil.UpdateAttribute(ref xDoc,fieldNode,"Min", fieldStats.Min==null?"":fieldStats.Min.ToString());
                    XmlDataUtil.UpdateAttribute(ref xDoc, fieldNode, "Max", fieldStats.Max == null ? "" : fieldStats.Max.ToString());
                    XmlDataUtil.UpdateAttribute(ref xDoc, fieldNode, "Median", fieldStats.Median == null ? "" : fieldStats.Median.ToString());
                    XmlDataUtil.UpdateAttribute(ref xDoc, fieldNode, "Mean", fieldStats.Mean == null ? "" : fieldStats.Mean.ToString());
                    XmlDataUtil.UpdateAttribute(ref xDoc, fieldNode, "SD",
                                                (fieldStats.StandardDeviation.HasValue
                                                     ? fieldStats.StandardDeviation.ToString()
                                                     : ""));
                }
            }

            return xNode;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="xNode"></param>
        /// <returns></returns>
        public override ResultBase Instantiate(XmlNode xNode)
        {
            if (xNode.Attributes.GetNamedItem("Type").Value == this.GetType().FullName)
            {
                TableStatsOutput output = new TableStatsOutput();
                output.OwnerWorkerInstanceID = new Guid(xNode.Attributes.GetNamedItem("WorkerID").Value);
                output.FinishTime = DateTime.Parse(xNode.Attributes.GetNamedItem("FinishTime").Value);

                output.TotalRecordCount = int.Parse(XmlDataUtil.GetAttributeValue(xNode, "TotalRecordCount", "0"));
                output.FieldStats = null;
                XmlNodeList fieldNodes = xNode.SelectNodes("//Field");
                if(fieldNodes !=null && fieldNodes.Count>0)
                {
                    output.FieldStats=new Dictionary<string, TableFieldStats<IComparable>>();
                    foreach(XmlNode fieldNode in fieldNodes)
                    {
                        string fieldName = XmlDataUtil.GetAttributeValue(fieldNode, "FieldName", "");
                        SqlDbType dbType =
                            (SqlDbType)
                            int.Parse(XmlDataUtil.GetAttributeValue(fieldNode, "DbType",
                                                                    ((int) SqlDbType.VarChar).ToString()));
                        int nonNullCount = int.Parse(XmlDataUtil.GetAttributeValue(fieldNode, "NonNullValueCount", "0"));
                        int distinctCount = int.Parse(XmlDataUtil.GetAttributeValue(fieldNode, "DistinctCount", "0"));
                        double coverage =
                            double.Parse(XmlDataUtil.GetAttributeValue(fieldNode, "NonNullValueCoverage", "0"));
                        string min = XmlDataUtil.GetAttributeValue(fieldNode, "Min", "0");
                        string max = XmlDataUtil.GetAttributeValue(fieldNode, "Max", "0");
                        string median = XmlDataUtil.GetAttributeValue(fieldNode, "Median", "0");
                        string mean = XmlDataUtil.GetAttributeValue(fieldNode, "Mean", "0");
                        string sdVal = XmlDataUtil.GetAttributeValue(fieldNode, "SD", "");
                        double sd=new double();
                        if(!string.IsNullOrEmpty(sdVal))
                        {
                            sd = double.Parse(sdVal);
                        }

                        TableFieldStats<IComparable> fieldStats = new TableFieldStats<IComparable>(dbType, nonNullCount,
                                                                                                   distinctCount,
                                                                                                   coverage, min, max,
                                                                                                   median, mean, sd);
                        output.FieldStats.Add(fieldName,fieldStats);
                    }
                }

                return output;
            }
            else
            {
                throw new Exception("Unable to instantiate output: invalid type specified in xml node");
            }
        }
    }
}
